library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)

# Figure 9.6
summary(factor(df$Q6D))
summary(factor(df$Q6C))
df2 <- df[df$Q11<5,]

df2$Q11T <- NA
df2$Q11T[df2$Q11>2] <- 0
df2$Q11T[df2$Q11<3] <- 1

# Important
df2$Q6D[df2$Q6D>3] <- NA
df2$Q6D[df2$Q6D==3] <- 0
df2$Q6D[df2$Q6D==2] <- 0.5
df2$Q6D[df2$Q6D==1] <- 1

df2$Q6C[df2$Q6C>3] <- NA
df2$Q6C[df2$Q6C==3] <- 0
df2$Q6C[df2$Q6C==2] <- 0.5
df2$Q6C[df2$Q6C==1] <- 1

df2 <- df2[df2$P_ASSIGN1==1,]

w2_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2
  )

f.6D <- svyby(~ Q6D, ~Q11T+party, w2_design, svymean, na.rm = TRUE)
f.6C <- svyby(~ Q6C, ~Q11T+party, w2_design, svymean, na.rm = TRUE)

# Humanitarian Missions
g.6D <- ggplot(f.6D, aes(x=factor(party),y=Q6D,fill=factor(Q11T),label=round(Q6D,digits=2)))+
  geom_col(position = position_dodge(1), width=0.5)+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat",'Independent',"Republican"))+
  xlab("")+
  ylab("Usefulness of Humanitarian Missions Abroad\n")

# Civil War
g.6C <- ggplot(f.6C, aes(x=factor(party),y=Q6C,fill=factor(Q11T),label=round(Q6C,digits=2)))+
  geom_col(position = position_dodge(1), width=0.5)+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat",'Independent',"Republican"))+
  xlab("")+
  ylab("Usefullness of Disaster Relief Missions\n")

grid.arrange(g.6D,g.6C,ncol=2)
